import {ajax, toast, promptBox, formDownload, getMultiLang} from 'nc-lightapp-front';
import requestApi from '../requestApi';
import {setTableExtendCol} from "ssccommon/components/profile";
import { get, forIn } from 'lodash-es';

//保存
let saveBtnEventConfig = {
    click(props) {

        let bool = props.form.isCheckNow('rule_code');
        if (!bool) return;

        let data = props.editTable.getAllData("rule_data");
        let formData = props.form.getAllFormValue('rule_code');
        formData.areacode = 'rule_code';
        if (formData.rows && formData.rows.length && formData.rows[0] && formData.rows[0].values) {
            Object.keys(formData.rows[0].values).forEach(key => {
                if (key === 'ruleobj_name') { // 分摊对象取值特殊处理
                    formData.rows[0].values['ruleobj_name'].value = formData.rows[0].values['ruleobj_name'].display + '#' + formData.rows[0].values['ruleobj_name'].value;
                }
            })
        }

        let meta = props.meta.getMeta();
        let multiLang = props.MutiInit.getIntl(2011);
        let requireKeys = [];

        meta['rule_data'].items.forEach((item) => {
            if (item.visible) {
                requireKeys.push(item.attrcode);
            }
        });

        let newrows = [];
        let hasErrorMsg = null;
        data.rows.forEach((row) => {
            if (requireKeys.findIndex(key => row.values[key].value == '' || row.values[key].value == null) > -1) { // 必填字段取值为空判断
                hasErrorMsg = true;
            } else {
                newrows.push(row);
            }
        });


        if (data.rows.length == 0) {
            toast({content: multiLang.get('201101BXBJ-0007'), color: 'warning'});//'保存数据不能为空!'
            return;
        }

        if (hasErrorMsg) {
            toast({content: multiLang.get('201103FTGZ-0001'), color: 'warning'});//'请完善分摊规则明细必填项!'
            return;
        }

        let bdata = {
            pageid: props.getPageCode(),
            head: {
                rule_code: formData,
            },
            body: {
                rule_data: {
                    rows: newrows,
                    areacode: 'rule_data',
                    areaType: 'table'
                }
            }
        };

        requestApi.save({
            data: bdata,
            success: async (resData) => {
                let data = {
                    data: {
                        head: resData.data.head,
                        body: bdata.body
                    }
                };
                setMetaDataFromTreeNode(data, props);
                // 放开左树禁用
                this.setState({treeSearchDisabled: false, refreshStatus: 'browse'});

                // 获取左侧树
                let treeData = await new Promise(resolve => {
                    requestApi.getTreeData({
                        data: {},
                        success(data) {
                            resolve(data);
                        }
                    });
                });
                // 左树数据打平
                let treenode = (treeData.data && treeData.data[1] || []).map(item => {
                    item.pid = null;
                    item.refname = item.refname || item.name;
                    return item;
                });

                if (treenode && treenode.length === 0) return;

                let {syncTree} = props;
                let {setSyncTreeData} = syncTree;
                let newTree = syncTree.createTreeData(treenode); //创建树 组件需要的数据结构
                setSyncTreeData('tree1', newTree);
                // 获取表单的pk_sharerule
                let pk_sharerule = props.form.getFormItemsValue('rule_code', 'pk_sharerule');
                // 选中左树选中项
                syncTree.setNodeSelected('tree1', pk_sharerule.value);

                this.pubMessage.saveSuccess();

            }
        })
    }
};
let tableBtnEventMapping = {
    /**
     * 新增行
     */
    AddLine: {
        click: props => {
            props.editTable.addRow('rule_data');
        }
    },
    /**
     * 删除行
     */
    DelLine: {
        click: props => {
            let activeItem = props.editTable.getClickRowIndex('rule_data');
            if (!activeItem) return;
            props.editTable.deleteTableRowsByIndex('rule_data', activeItem.index);
        }
    }
};
let btnEventMapping = {
    /*
    * 新增操作
    * 1、展示保存、取消按钮；
    * 2、其他的隐藏按钮；
     */
    Add: {
        click(props) {
            props.button.setButtonsVisible({
                Add: false,
                Edit: false,
                Save: true,
                Cancel: true,
                Delete: false,
                Refresh: false,
                AddLine: true,
                DelLine: true
            });
            props.button.setButtonDisabled('1001Z3100000000004OR', true);
            this.setState({treeSearchDisabled: true, refreshStatus: 'nobrowse'});
            props.form.EmptyAllFormValue('rule_code');
            props.form.setFormItemsValue('rule_code', {rule_type: {display: '按比例分摊', value: '2'}}); // 新增规则 默认分摊方式：按比例分摊
            props.form.setFormStatus('rule_code', 'edit');
            props.editTable.setStatus('rule_data', 'edit');
            props.editTable.setTableData('rule_data', {rows: []});
            const meta = props.meta.getMeta();
            if (meta && meta.rule_data && meta.rule_data.items && meta.rule_data.items.length) {
                meta.rule_data.items.forEach(item => {
                    if (item.attrcode === 'share_ratio') {
                        props.editTable.showColByKey('rule_data', item.attrcode);
                    } else {
                        props.editTable.hideColByKey('rule_data', item.attrcode);
                    }
                });
            }
        }
    },
    /*
    * 修改操作
    * 1、展示新增按钮；
    * 2、其他的隐藏按钮；
     */
    Edit: {
        click(props) {
            props.button.setButtonsVisible({
                Add: false,
                Edit: false,
                Save: true,
                Cancel: true,
                Delete: false,
                Refresh: false,
                AddLine: true,
                DelLine: true
            });
            this.setState({treeSearchDisabled: true, refreshStatus: 'nobrowse'});
            props.form.setFormStatus('rule_code', 'edit');
            props.editTable.setStatus('rule_data', 'edit');
        }
    },
    /*
    * 取消操作
    * 1、展示新增按钮；
    * 2、其他的隐藏按钮；
     */
    Cancel: {
        click(props) {
            props.button.setButtonsVisible({
                Add: true,
                Edit: true,
                Save: false,
                Cancel: false,
                Delete: false,
                Refresh: false,
                AddLine: false,
                DelLine: false
            });

            props.form.setFormStatus('rule_code', 'browse');
            this.setState({treeSearchDisabled: false, refreshStatus: 'browse'});
            props.editTable.cancelEdit('rule_data');
            const meta = props.meta.getMeta();
            if (meta && meta.rule_data && meta.rule_data.items && meta.rule_data.items.length) {
                meta.rule_data.items.forEach(item => {
                    props.editTable.hideColByKey('rule_data', item.attrcode);
                });
            }
            let {syncTree} = props;
            if (syncTree.getSelectNode('tree1') && syncTree.getSelectNode('tree1').refpk) {
                let reqData = {
                    pagecode: props.getPageCode(),
                    pk: syncTree.getSelectNode('tree1').refpk,
                };
                requestApi.getTableData({
                    data: reqData,
                    success: (data) => {
                        setMetaDataFromTreeNode(data, props);
                    }
                });
            }
        }
    },
    /**
     * 删除操作
     */
    Delete: {
        click(props) {
            props.button.setButtonsVisible({
                AddLine: false,
                DelLine: false
            });
            const multiLang = props.MutiInit.getIntl(2011);

            promptBox({
                color: 'warning',
                title: multiLang && multiLang.get('2011-0004') /* 国际化处理： 删除*/,
                content: multiLang && multiLang.get('2011-0005') /* 国际化处理： ​​确定要删除所选数据吗？*/,
                noFooter: false,
                noCancelBtn: false,
                beSureBtnName: multiLang && multiLang.get('2011-0003'),
                cancelBtnName: multiLang && multiLang.get('2011-0002'),
                beSureBtnClick: () => {
                    const { syncTree } = props;
                    if (syncTree.getSelectNode('tree1') && syncTree.getSelectNode('tree1').refpk) {
                        let reqData = {
                            pagecode: props.getPageCode(),
                            pk: syncTree.getSelectNode('tree1').refpk
                        };
                        requestApi.remove({
                            data: reqData,
                            success: () => {
                                toast({ content: multiLang.get('201101BXBJ-0010') });
                                requestApi.getTreeData({
                                    data: {},
                                    success(data) {
                                        let treenode = ((data.data && data.data[1]) || []).map((item) => {
                                            item.pid = null;
                                            item.refname = item.refname || item.name;
                                            return item;
                                        });

                                        let newTree = syncTree.createTreeData(treenode); //创建树 组件需要的数据结构
                                        syncTree.setSyncTreeData('tree1', newTree);
                                        
                                        if (treenode && treenode.length === 0) {
                                            setMetaDataFromTreeNode({}, props);
                                            return
                                        }

                                        syncTree.setNodeSelected('tree1', treenode[0].refpk);
                                        //设置表格数据
                                        let reqData = {
                                            pagecode: props.getPageCode(),
                                            pk: treenode[0].refpk || treenode[0].refcode
                                        };
                                        requestApi.getTableData({
                                            data: reqData,
                                            success: (data) => {
                                                setMetaDataFromTreeNode(data, props);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }
    }
};

/**
 * 树节点选择事件
 */
async function treeSelectEvent(key, item) {

    //设置表格数据
    let reqData = {
        pagecode: this.props.getPageCode(),
        pk: item.refpk || item.refcode,
    };
    let data = await new Promise(resolve => {
        requestApi.getTableData({
            data: reqData,
            success: (data) => {
                resolve(data);
            }
        });
    });
    setMetaDataFromTreeNode(data, this.props);
}

// 根据加载的分摊详情 表单赋值 表格赋值 按钮设置
function setMetaDataFromTreeNode(data, props) {
    const headValues = get(data, 'data.head.rule_code.rows[0].values', null);
    const bodyValues = get(data, 'data.body.rule_data.rows[0].values', null);
    const hideArr = [];
    const showArr = [];
    if (!headValues || !bodyValues) {
        props.form.EmptyAllFormValue('rule_code');
        props.form.setFormStatus('rule_code', 'browse');

        props.editTable.setTableData('rule_data', { rows: [] });
        props.editTable.setStatus('rule_data', 'browse');
        return;
    };
    let formData = data.data.head.rule_code;
    (formData.rows || []).forEach((item) => {
        if (
            item.values &&
            item.values.ruleobj_name &&
            item.values.ruleobj_name.value &&
            item.values.ruleobj_name.value.includes('#')
        ) {
            item.values.ruleobj_name['display'] = item.values.ruleobj_name.value.split('#')[0];
            item.values.ruleobj_name['value'] = item.values.ruleobj_name.value.split('#')[1];
        }
    });
    props.form.setAllFormValue({ rule_code: formData });
    props.form.setFormStatus('rule_code', 'browse');

    props.editTable.setTableData('rule_data', data.data.body.rule_data);
    props.editTable.setStatus('rule_data', 'browse');

    forIn(bodyValues, (item, key) => {
        if (key === headValues.ruleobj_name.value) {
            showArr.push(key);
        } else {
            hideArr.push(key);
        }
    });
    props.editTable.showColByKey('rule_data', showArr);
    props.editTable.hideColByKey('rule_data', hideArr);

    if (headValues.rule_type) {
        switch (headValues.rule_type.value) {
            case '1': // 平均分摊
                props.editTable.hideColByKey('rule_data', ['assume_amount', 'share_ratio']);
                break;
            case '2': // 按比例分摊
                props.editTable.hideColByKey('rule_data', 'assume_amount');
                props.editTable.showColByKey('rule_data', 'share_ratio');
                break;
            case '3': // 按金额分摊
                props.editTable.hideColByKey('rule_data', 'share_ratio');
                props.editTable.showColByKey('rule_data', 'assume_amount');
                break;
            default:
                // 空状态
                props.editTable.hideColByKey('rule_data', ['assume_amount', 'share_ratio']);
                break;
        }
    }

    // 选择左侧规则节点 控制操作按钮
    props.button.setButtonsVisible({
        Add: true,
        Edit: true,
        Save: false,
        Cancel: false,
        Delete: true,
        Refresh: false,
        AddLine: false,
        DelLine: false
    });
}

export default {saveBtnEventConfig, treeSelectEvent, btnEventMapping, tableBtnEventMapping, setMetaDataFromTreeNode}


